package auth

import (
	"github.com/kataras/iris/v12"
	"iris-demo/core"
)

type AuthController struct {
	service UserService
}

func (c AuthController) Register(ctx iris.Context) {
	var createForm UserCreateForm
	if err := core.ValidForm(ctx, &createForm); err != nil {
		ctx.StatusCode(iris.StatusBadRequest)
		_, _ = ctx.JSON(iris.Map{"msg": "400: " + err.Error() + "！"})
	} else {
		if user, err := c.service.Create(createForm); err != nil {
			ctx.StatusCode(iris.StatusInternalServerError)
		} else {
			_, _ = ctx.JSON(user)
		}
	}
}

func (c AuthController) Login(ctx iris.Context) {
	var loginForm UserLoginForm
	if err := core.ValidForm(ctx, &loginForm); err != nil {
		ctx.StatusCode(iris.StatusBadRequest)
		_, _ = ctx.JSON(iris.Map{"msg": "400: " + err.Error() + "！"})
	} else {
		if user, ok := c.service.GetByUsername(loginForm.Username); !ok {
			ctx.StatusCode(iris.StatusBadRequest)
			_, _ = ctx.JSON(iris.Map{"msg": "400: 用户名未注册！"})
		} else {
			if core.VerifyPassword(user.Password, loginForm.Password) != nil {
				ctx.StatusCode(iris.StatusBadRequest)
				_, _ = ctx.JSON(iris.Map{"msg": "400: 用户名或密码错误！"})
			} else {
				if token, err := user.CreateJwtToken(); err != nil {
					ctx.StatusCode(iris.StatusInternalServerError)
				} else {
					_, _ = ctx.JSON(token)
				}
			}
		}
	}
}

func (c AuthController) ChangePassword(ctx iris.Context) {
	if id, err := ctx.Params().GetUint("id"); err != nil {
		ctx.StatusCode(iris.StatusNotFound)
	} else {
		if user, ok := c.service.GetById(id); !ok {
			ctx.StatusCode(iris.StatusNotFound)
		} else {
			var passwordForm UserChangePasswordForm
			if err := core.ValidForm(ctx, &passwordForm); err != nil {
				ctx.StatusCode(iris.StatusBadRequest)
				_, _ = ctx.JSON(iris.Map{"msg": "400: " + err.Error() + "！"})
			} else {
				if err := c.service.Update(&user, iris.Map{"password": passwordForm.Password}); err != nil {
					ctx.StatusCode(iris.StatusInternalServerError)
				} else {
					_, _ = ctx.JSON(user)
				}
			}
		}
	}
}

type UserController struct {
	service UserService
}

func (c UserController) List(ctx iris.Context) {
	query := ctx.URLParam("query")
	_, _ = ctx.JSON(c.service.QuerySet(query))
	//if users, err := c.service.QuerySet(query); err != nil {
	//	ctx.StatusCode(iris.StatusInternalServerError)
	//} else {
	//	_, _ = ctx.JSON(users[0 ])
	//}
}
